package com.myCommon.security.filter;

import com.myCommon.security.entity.LoginUser;
import com.myCommon.util.customerException.CustomerExceptionHandler;
import com.myCommon.util.jwt.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;


@Component
public class JwtAuthTokenFilter extends OncePerRequestFilter {
      
      @Autowired
      private RedisTemplate redisTemplate;
      
      @Autowired
      private HandlerExceptionResolver handlerExceptionResolver;
      
      
      @Override
      protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
            String token = request.getHeader("token");
            if (!StringUtils.hasText(token)) {
                  filterChain.doFilter(request, response);
                  return;
            }
            Claims claims = null;
            String userId = null;
            try {
                  claims = JwtUtil.parseJWT(token);
                  userId = claims.getSubject();
            } catch (Exception e) {
                  handlerExceptionResolver.resolveException(request, response, null, new CustomerExceptionHandler("token不合法"));
            }
            LoginUser loginUser = (LoginUser) redisTemplate.opsForValue().get("login:" + userId);
            if (Objects.isNull(loginUser)) {
                 handlerExceptionResolver.resolveException(request, response, null, new CustomerExceptionHandler("用户未登录"));
                 return;
            }
            
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            filterChain.doFilter(request, response);
      }
      
}
